// pages/exam/exam-wrong/exam-wrong.ts
import { Question } from '../../../utils/examTypes';
import { ExamUtils } from '../../../utils/examUtils';

Page({
  data: {
    questions: [] as Question[], // 题目列表
    currentIndex: 0, // 当前题目索引
    progress: "" as string, // 进度百分比
    animationConfig: {
      duration: 300,
      timingFunction: 'ease-in-out'
    },
    selectedOptions: {}, // 记录每道题的选择 {题号: 选项}
    optionClassMapList: [] as { [key: string]: string }[] // 选项样式映射列表
  },

  onLoad() {
    this.loadWrongQuestions();
  },

  // 加载错题列表
  async loadWrongQuestions() {
    this.setData({ loading: true });
    wx.showLoading({ title: '加载错题中...', mask: true });

    try {
      const wrongQuestions = await this.fetchWrongQuestionList();
      
      // 转换题目数据格式
      const formattedQuestions = wrongQuestions.map((q: any) => {
        return {
          questionId: q.questionId,
          questionNo: q.questionNo,
          content: ExamUtils.stripHtmlTags(q.content),
          options: q.options.map((opt: any) => ({
            questionNo: opt.questionNo,
            optionNo: opt.optionNo,
            content: ExamUtils.stripHtmlTags(opt.content),
          })),
          correctAnswer: q.correctAnswer, // 正确答案
          answerAnalysis: ExamUtils.stripHtmlTags(q.answerAnalysis),
          userAnswer: q.userAnswer || '', // 用户选择的选项
          showExplanation: false // 是否显示解析
        };
      });

      // 初始化选项样式映射列表
      const optionClassMapList = formattedQuestions.map(question => {
        const map: { [key: string]: string } = {};
        question.options.forEach(option => {
          map[option.optionNo] = this.getOptionClass(question, option);
        });
        return map;
      });

      this.setData({
        questions: formattedQuestions,
        currentIndex: 0,
        progress: ExamUtils.calculateProgress(0, formattedQuestions.length),
        optionClassMapList
      });

    } catch (error) {
      console.error('加载错题失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error',
        duration: 2000
      });
    } finally {
      this.setData({ loading: false });
      wx.hideLoading();
    }
  },

  // 从网络获取错题列表
  async fetchWrongQuestionList(): Promise<any[]> {
    const app = getApp<IAppOption>();
    
    return new Promise((resolve, reject) => {
      wx.request({
        url: app.buildApiUrl('/api/paper-questions/wrong-question-list'),
        method: 'GET',
        header: {'Authorization': wx.getStorageSync('token')},
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data as any[]);
          } else {
            reject(new Error(`请求失败，状态码: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },

  // 滑动切换题目
  handleSwiperChange(e: any) {
    const current = e.detail.current;
    this.updateCurrentIndex(current);
  },
  
  prevQuestion() {
    const { currentIndex } = this.data;
    if (currentIndex > 0) {
      this.updateCurrentIndex(currentIndex - 1);
    }
  },
  
  nextQuestion() {
    const { currentIndex, questions } = this.data;
    if (currentIndex < questions.length - 1) {
      this.updateCurrentIndex(currentIndex + 1);
    }
  },
  
  // 更新当前索引
  updateCurrentIndex(index: number) {
    this.setData({
      currentIndex: index,
      progress: ExamUtils.calculateProgress(index, this.data.questions.length)
    });
  },

  // 获取选项的样式类
  getOptionClass(question: any, option: any): string {
    if (question.userAnswer != null && question.correctAnswer === option.optionNo) {
      return 'corrected';
    } else if (question.userAnswer === option.optionNo) {
      return 'incorrected';
    }
    return '';
  },

  // 计算指定题目的选项样式类映射
  calculateOptionClassMap(questionIndex: number) {
    const { questions, optionClassMapList } = this.data;
    const question = questions[questionIndex];
    
    // 创建新的样式映射对象
    const newOptionClassMap: { [key: string]: string } = {};
    question.options.forEach(option => {
      newOptionClassMap[option.optionNo] = this.getOptionClass(question, option);
    });
    
    // 更新指定索引的样式映射
    const newOptionClassMapList = [...optionClassMapList];
    newOptionClassMapList[questionIndex] = newOptionClassMap;
    
    this.setData({
      optionClassMapList: newOptionClassMapList
    });
  },

  // 选择选项
  selectOption(e: any) {
    const { option, index } = e.detail;
    const { questions } = this.data;

    // 更新选择状态
    const updatedQuestions = [...questions];
    updatedQuestions[index] = {
      ...updatedQuestions[index],
      userAnswer: option,
      showExplanation: true
    };

    this.setData({
      questions: updatedQuestions
    });
    
    // 只更新当前题目的选项样式
    this.calculateOptionClassMap(index);
    
    const isCorrect = updatedQuestions[index].correctAnswer == option;

    // 如果答对了，自动下一题
    if (isCorrect) {
      const { currentIndex, questions } = this.data;
      if (currentIndex < questions.length - 1) {
        this.updateCurrentIndex(currentIndex + 1);
      }
    }
  },

  // 切换解析显示
  toggleExplanation(e: any) {
    const { index } = e.detail;
    const { questions } = this.data;
    const updatedQuestions = [...questions];
    updatedQuestions[index].showExplanation = !updatedQuestions[index].showExplanation;

    this.setData({
      questions: updatedQuestions
    });
  },

  getOptionStatus(question: any, option: any): string {
    return ExamUtils.getOptionStatus(question, option);
  }
});